package ink.tiptop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.tiptop.common.domain.rsp.SucceedResponse;
import ink.tiptop.dto.req.auth.ChangePasswordZjfAuthUserInfoRequest;
import ink.tiptop.persist.domain.entity.ZjfAuthUserInfoEntity;
import ink.tiptop.dto.req.auth.AddZjfAuthUserInfoRequest;
import ink.tiptop.dto.req.auth.LoginZjfAuthUserInfoRequest;
import ink.tiptop.enums.EResp;
import ink.tiptop.common.domain.WebworkResponse;
import ink.tiptop.dto.resp.auth.LoginZjfAuthUserInfoResponse;
import ink.tiptop.common.cache.ICache;
import ink.tiptop.common.ContextHolder;
import ink.tiptop.exception.JDTException;
import ink.tiptop.exception.JDTExceptionMsg;
import ink.tiptop.constant.AuthConst;
import ink.tiptop.persist.dao.ZjfAuthUserInfoMapper;
import ink.tiptop.common.domain.rsp.BodyResponse;
import ink.tiptop.common.domain.rsp.Response;
import ink.tiptop.service.ZjfAuthUserInfoService;
import ink.tiptop.utils.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * 用于用户登录的信息(ZjfAuthUserInfoEntity)表服务实现类
 *
 * @author makejava
 * @since 2020-06-21 20:35:17
 */
@Slf4j
@Service("zjfAuthUserInfoService")
public class ZjfAuthUserInfoServiceImpl implements ZjfAuthUserInfoService {
    @Resource
    private ZjfAuthUserInfoMapper zjfAuthUserInfoMapper;

    @Autowired
    private ICache cache;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ZjfAuthUserInfoEntity queryById(Integer id) {
        return zjfAuthUserInfoMapper.selectById(id);
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     */
    @Override
    public List<ZjfAuthUserInfoEntity> queryAll() {
        return zjfAuthUserInfoMapper.selectList(null);
    }

    /**
     * 新增数据
     *
     * @param zjfAuthUserInfoEntity 实例对象
     * @return 实例对象
     */
    @Override
    public ZjfAuthUserInfoEntity insert(ZjfAuthUserInfoEntity zjfAuthUserInfoEntity) {
        zjfAuthUserInfoMapper.insert(zjfAuthUserInfoEntity);
        return zjfAuthUserInfoEntity;
    }

    /**
     * 修改数据
     *
     * @param zjfAuthUserInfoEntity 实例对象
     * @return 实例对象
     */
    @Override
    public ZjfAuthUserInfoEntity update(ZjfAuthUserInfoEntity zjfAuthUserInfoEntity) {
        this.zjfAuthUserInfoMapper.updateById(zjfAuthUserInfoEntity);
        return this.queryById(zjfAuthUserInfoEntity.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return zjfAuthUserInfoMapper.deleteById(id) > 0;
    }

    @Override
    public Response login(LoginZjfAuthUserInfoRequest request) {
        // 账号密码查询用户数据
        ZjfAuthUserInfoEntity condition = new ZjfAuthUserInfoEntity();
        condition.setUser(request.getUser());
        condition.setIsDelete(1);

        QueryWrapper<ZjfAuthUserInfoEntity> queryWrapper = new QueryWrapper<>(condition);
        List<ZjfAuthUserInfoEntity> infos = zjfAuthUserInfoMapper.selectList(queryWrapper);
        // 没有找到
        if (infos.isEmpty()) {
            return WebworkResponse.failed(EResp.EUserAuth.ERROR_EXIST_NOT);
        }
        if (!infos.get(0).getPass().equals(request.getPass())) {
            return WebworkResponse.failed(EResp.EUserAuth.ERROR_PASS);
        }
        ThreadLocal<HttpServletRequest> localRequest = ContextHolder.getLocalRequest();
        // 添加sessionId,info到缓存信息中,并添加过期时间
        HttpSession session = localRequest.get().getSession(true);

        ZjfAuthUserInfoEntity zjfAuthUserInfoEntity = infos.get(0);
        LoginZjfAuthUserInfoResponse resp = new LoginZjfAuthUserInfoResponse();
        BeanUtils.copyProperties(zjfAuthUserInfoEntity, resp);
        // 不管有没有登录过,都重置缓存时间
        session.setAttribute(AuthConst.SESSION_ID, resp.getUser());
        boolean b = cache.setVal(AuthConst.SESSION_ID, resp, AuthConst.CACHE_TYPE);
        if (b) {
            log.info("sessionId:{},添加到缓存成功", AuthConst.SESSION_ID);
        }

//        addCookie(resp);
        return new BodyResponse<>(resp);
    }

    private void addCookie(LoginZjfAuthUserInfoResponse resp) {
        ThreadLocal<HttpServletResponse> response = ContextHolder.getLocalResponse();
        HttpServletResponse httpServletResponse = response.get();

        Cookie userCookie = new Cookie("USER", JSON.toJSONString(resp));
        // cookie不能存json数据,校验拦截了"
        httpServletResponse.addCookie(userCookie);
    }

    @Override
    public Response add(AddZjfAuthUserInfoRequest request) {
        ZjfAuthUserInfoEntity condition = new ZjfAuthUserInfoEntity();
        condition.setUser(request.getUser());
        if (zjfAuthUserInfoMapper.selectCount(new QueryWrapper<>(condition)) > 0) {
            return WebworkResponse.failed(EResp.EUserAuth.ERROR_EXIST);
        }
        ZjfAuthUserInfoEntity zjfAuthUserInfoEntity = new ZjfAuthUserInfoEntity();
        BeanUtils.copyProperties(request, zjfAuthUserInfoEntity);
        zjfAuthUserInfoEntity.setIsDelete(1);
        zjfAuthUserInfoEntity.setCreateTime(new Date());
        int insert = zjfAuthUserInfoMapper.insert(zjfAuthUserInfoEntity);
        if (insert > 0) {
            return WebworkResponse.SUCCEED;
        }
        return WebworkResponse.failed(EResp.EUserAuth.ERROR_ADD);
    }

    @Override
    public Response logout() {
        boolean b = cache.del(AuthConst.SESSION_ID, AuthConst.CACHE_TYPE);
        if (b) {
            log.info("sessionId:{},删除缓存成功", AuthConst.SESSION_ID);
            return WebworkResponse.SUCCEED;
        }
        return WebworkResponse.failed(EResp.EUserAuth.ERROR_LOGOUT);
    }

    @Override
    public void checkUserExist(String user) {
        ZjfAuthUserInfoEntity entity = new ZjfAuthUserInfoEntity();
        entity.setUser(user);
        if (zjfAuthUserInfoMapper.selectCount(new QueryWrapper<>(entity)) == 0) {
            JDTException.throwException(JDTExceptionMsg.getError(EResp.EUserAuth.ERROR_EXIST_NOT));
        }
    }

    @Override
    public Response changePasswordByUserName(ChangePasswordZjfAuthUserInfoRequest request) {
        if (!request.getNewPass().equals(request.getConfirmPass())) {
            JDTException.throwException(JDTExceptionMsg.getError(EResp.EUserAuth.ERROR_CONFIRM_PASSWORD));
        }
        ZjfAuthUserInfoEntity zjfAuthUserInfoEntity = zjfAuthUserInfoMapper.selectOne(new QueryWrapper<>(new ZjfAuthUserInfoEntity().setUser(request.getUser())));
        if (zjfAuthUserInfoEntity == null) {
            JDTException.throwException(JDTExceptionMsg.getError(EResp.EUserAuth.ERROR_EXIST_NOT));
        }
        if (!zjfAuthUserInfoEntity.getPass().equals(request.getPass())) {
            JDTException.throwException(JDTExceptionMsg.getError(EResp.EUserAuth.ERROR_PASS));
        }

        int update = zjfAuthUserInfoMapper.updateById(new ZjfAuthUserInfoEntity().setId(zjfAuthUserInfoEntity.getId()).setPass(request.getNewPass()));

        if (update > 0) {
            return WebworkResponse.SUCCEED;
        }
        return WebworkResponse.failed(EResp.EUserAuth.ERROR_UPDATE);
    }
}